<script setup>
import LfDialog from '@/components/commonUI/LfDialog.vue'
import { useHeaderStore } from '@/views/Layout/Header/stores/headerStore'
import { useMyInfoQuery } from '@/composables/useUserInfoQuery'
import CameraIcon from '../svgComponents/CameraIcon.vue'
import ImgButton from './components/ImgButton.vue'
import LfButton from '@/components/commonUI/LfButton.vue'
import { useUpdateUserInfoMutation } from '@/composables/useUserInfoQuery'
import LfFormItem from '../commonUI/LfFormItem.vue'
import { ElSelect, ElOption } from 'element-plus'
import { postUploadFile } from '@/axios/api/upload'
import TagsManager from './components/TagsManager.vue'
import { useUserInfoQuery } from '@/composables/useUserInfoQuery'
const headerStore = useHeaderStore()

const avatarImgPreview = ref('')
const avatarImgUpload = ref('')

const bgImgPreview = ref('')
const bgImgUpload = ref('')

const close = () => {
  headerStore.hideUserInfoEdit()
}

const { userInfo, refetchUserInfo } = useMyInfoQuery()
const { refetch: refetchUserInfoById } = useUserInfoQuery(userInfo.value.result.uid)
const mutation = useUpdateUserInfoMutation()

const editInfo = ref({
  username: '',
  gender: '',
  bgImg: '',
  avatar: '',
  intro: '',
  tagStr: [],
})

const changeTags = (tags) => {
  editInfo.value.tagStr = tags
}

onMounted(() => {
  if (userInfo.value) {
    editInfo.value.username = userInfo.value.result.username
    editInfo.value.gender = userInfo.value.result.gender
    editInfo.value.bgImg = userInfo.value.result.bgImg
    editInfo.value.avatar = userInfo.value.result.avatar
    editInfo.value.intro = userInfo.value.result.intro
    editInfo.value.tagStr = userInfo.value.result.tagStr
  }
})

const save = async () => {
  // 没有修改的值不传
  const params = {}
  for (const key in editInfo.value) {
    if (editInfo.value[key] !== userInfo.value.result[key]) {
      params[key] = editInfo.value[key]
    }
  }

  if (avatarImgUpload.value) {
    const formData = new FormData()
    formData.append('Image', avatarImgUpload.value)

    const res = await postUploadFile(formData)
    params.avatar = res.result
  }

  if (bgImgUpload.value) {
    const formData = new FormData()
    formData.append('Image', bgImgUpload.value)

    const res = await postUploadFile(formData)
    params.bgImg = res.result
  }

  mutation.mutate(params, {
    onSuccess: () => {
      refetchUserInfo()
      refetchUserInfoById(userInfo.value.result.uid)
      close()
    },
  })
}

const handleNameChange = (value) => {
  editInfo.value.username = value
}

const handleIntroChange = (value) => {
  editInfo.value.intro = value
}

const handleImgUpload = (domId) => {
  const fileInput = document.getElementById(domId)
  fileInput.click()
}

const readAndUploadAvatarImg = (event) => {
  const files = event.target.files
  avatarImgUpload.value = files[0]

  const reader = new FileReader()

  reader.onload = function (event) {
    avatarImgPreview.value = event.target.result // 添加到预览数组
  }
  reader.readAsDataURL(files[0])
}

const readAndUploadBgImg = (event) => {
  const files = event.target.files
  bgImgUpload.value = files[0]

  const reader = new FileReader()

  reader.onload = function (event) {
    bgImgPreview.value = event.target.result // 添加到预览数组
  }
  reader.readAsDataURL(files[0])
}

const options = [
  {
    value: 2,
    label: '女',
  },
  {
    value: 1,
    label: '男',
  },
  // {
  //   value: 0,
  //   label: '保密',
  // },
]
</script>

<template>
  <LfDialog :isShow="headerStore.isShowUserInfoEdit" @close="close">
    <div class="flex flex-col gap-4 p-3 px-1">
      <div class="flex justify-between px-3">
        <div class="text-lg font-bold rounded-lg">编辑资料</div>
        <div class="flex gap-4 items-center">
          <LfButton @click="save" type="primary">保存</LfButton>
          <img @click="close" src="/imgs/commonIcons/close.svg" alt="" class="w-[25px] h-[25px] cursor-pointer" />
        </div>
      </div>

      <div class="w-full bg-[--fill-b] h-[150px] relative">
        <img
          v-if="bgImgPreview || userInfo?.result?.bgImg"
          :src="bgImgPreview || userInfo?.result?.bgImg"
          class="w-full h-full object-cover" />

        <div
          class="absolute left-[50%] top-[50%] translate-x-[-50%] translate-y-[-50%] flex gap-6 w-full h-full bg-[#00000030] flex-cc">
          <div>
            <input type="file" :onchange="readAndUploadBgImg" id="bgImgUpload" accept="image/*" />
            <ImgButton @click="handleImgUpload('bgImgUpload')">
              <CameraIcon class="w-[20px] h-[20px]" />
            </ImgButton>
          </div>
        </div>
      </div>

      <div
        class="w-[100px] h-[100px] rounded-full mt-[-60px] ml-[10px] border-4 border-[--line-0] overflow-hidden relative">
        <img :src="avatarImgPreview || userInfo?.result?.avatar" alt="" />
        <div
          class="absolute left-[50%] top-[50%] translate-x-[-50%] translate-y-[-50%] bg-[#00000030] w-full h-full flex-cc">
          <input type="file" :onchange="readAndUploadAvatarImg" id="avatarImgUpload" accept="image/*" />
          <ImgButton @click="handleImgUpload('avatarImgUpload')">
            <CameraIcon class="w-[20px] h-[20px]" />
          </ImgButton>
        </div>
      </div>

      <div class="flex flex-col gap-6 px-3">
        <LfFormItem label="昵称" :value="editInfo.username" @change="handleNameChange" maxLength="12" />

        <div>
          <div class="text-sm text-[--text-3] mb-2">性别</div>
          <el-select v-model="editInfo.gender" placeholder="Select" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <LfFormItem
          label="个性签名"
          :value="editInfo.intro"
          type="textarea"
          @change="handleIntroChange"
          :maxLength="20" />

        <TagsManager :tags="editInfo.tagStr" @change="changeTags" />
      </div>
    </div>
  </LfDialog>
</template>

<style scoped lang="scss">
:deep(.el-select__wrapper.is-focused) {
  box-shadow: 0 0 0 1px var(--line-b) inset !important;
}
</style>
